#include "server_main.h"

int epfd;
//主进程
void sighandle(int i){
    int num = 1;
    write(exitpipe[1],&num,sizeof(int));
}

//设置信号管道
void set_sig_pipe(){
    signal(SIGUSR1,sighandle);
    pipe(exitpipe);
}


//加载各模块
void server_module_loading(){
    //加载数据库
    db_init();
}

//初始化
void server_work(){
    close(exitpipe[1]);
    log_init();
    //创建线程池
    struct epoll_event * events = epoll_init(&epfd);
    threadpool_t  *threadpool = (threadpool_t *)calloc(1,sizeof(threadpool_t));

    tp_init(threadpool,THREAD_POOL_SIZE);
    tp_start(threadpool);
    //建立监听套接字
    int listenfd = tcp_init(IP,PROT);
    //创建epoll实例
    epoll_add_fd(listenfd);
    epoll_add_fd(exitpipe[0]);
    
    while(1){
        int readnum = epoll_wait(epfd,events,EPOLL_EVENT_SIZE,-1);
        if(-1 == readnum)
            error_log("server_main.c:epoll_wait");
        printf("new fd : %d",readnum);
        syslog(LOG_INFO,"epoll_wait");
        if (0 < readnum)
        {
            for(int i = 0; i < EPOLL_EVENT_SIZE; i++){
                int readfd = events[i].data.fd;
                if(listenfd == readfd)//新连接
                    new_connect(listenfd,events,threadpool);
                //管道监听
                else if(exitpipe[0] == readfd)
                {
                    child_exit(listenfd,threadpool);
                    break;
                }else//旧连接，解析命令,创建任务
                {
                    make_task(readfd,threadpool);
                }
            }
        }
    }
    epoll_destroy(events);
    close(listenfd);
    free(threadpool);
    close(epfd);
    closelog();
}
